# -*- coding: utf-8 -*-
# Create your views here.

from wikicamp.wiki.models import Page, Tag
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django import forms
import markdown
import locale
import htmllib

locale.setlocale(locale.LC_ALL,"")

class SearchForm(forms.Form):
	text = forms.CharField(label="Enter Search Term")
	search_content = forms.BooleanField(label="Search Content",required=False)
	
def search_page(request):
	if request.method == "POST":
	    f = SearchForm(request.POST)
	    if not f.is_valid():
		return render_to_response("search.html",{"form":f})
	    else:
	        pages = Page.objects.filter(name__contains = f.cleaned_data["text"])
		contents = []
		if f.cleaned_data["search_content"]:
		    contents= Page.objects.filter(content__contains = f.cleaned_data["text"])
                return render_to_response("search.html",{"form":f,"pages":pages,"contents":contents})
		
	f = SearchForm()
	return render_to_response("search.html",{"form":f})
      
specialPages = {"SearchPage":search_page}

def view_page(request,page_name):
	if page_name in specialPages:
		return specialPages[page_name](request)
	try:
		page = Page.objects.get(pk=page_name)
		tags = page.tags.all()
		
	except Page.DoesNotExist:
		return render_to_response("create.html",{"page_name":page_name})
	
	content = page.content
	#print "type content _ : " + str(type(content))
	#content = unicode(content)
	return render_to_response("view.html",{"page_name":page_name,"content":markdown.markdown(content),"tags":tags})	

def edit_page(request,page_name):
	try:
		page = Page.objects.get(pk=page_name)
		content = page.content
		tags = " ".join([tag.name for tag in page.tags.all()])
	except Page.DoesNotExist:
		content = ""
		tags = ""
	return render_to_response("edit.html",{"page_name":page_name,"content":content,"tags":tags})

def save_page(request,page_name):
	content = request.POST["content"]
	tag_list = []
	if "tags" in request.POST:
		tags = request.POST["tags"]
		tag_list = [Tag.objects.get_or_create(name=tag)[0] for tag in tags.split()]
	try:
		page = Page.objects.get(pk=page_name)
		page.content = content
		for xtag in tag_list:
			page.tags.add(xtag)
	except Page.DoesNotExist:
		page = Page(name=page_name,content=content)
	

	page.save()
	return HttpResponseRedirect("/wikicamp/page/" + page_name + "/")

def view_tag(request,tag_name):
	tag = Tag.objects.get(pk=tag_name)
	pages = tag.page_set.all()
	
	return render_to_response("tag.html", {"tag_name":tag_name,"pages":pages})

